<?php
// +----------------------------------------------------------------------
// |商品管理
// +----------------------------------------------------------------------
// |Data:2016-06-24 下午3:32
// +----------------------------------------------------------------------
// |Author: 吕志雄 <870923001@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Common\Controller\AdminCommonController;

class ProductController extends AdminCommonController{
    private $model;
    
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = D('Admin/Product');
    }

    public function index(){
        $status = I('get.status',0,'intval');
        $stock = I('get.stock',0,'intval');
        $cid = I('get.cid',0,'intval');
        $sort = I('get.sort');//排序方式
        $shop_id = I('get.shop_id',0,'intval');

        empty($sort) && $sort = 'edit_time';
        $order = $sort.' desc';

        $map = array();

        if(!$this->isSysAdmin){
            $map['uid'] = $this->manage_id;
        }

        $keywords = urldecode(I('get.keywords','','trim'));//关键词
        if(!empty($keywords)){
            $map['title|desc'] = array('like','%'.$keywords.'%');
        }
        !empty($status) && $map['is_on'] = $status;
        if($stock==1) $map['store'] = 0;
        else if($stock==2) $map['store'] = array('gt',0);

        $price_type = intval(I('get.price'));
        if($price_type==1){
            $order = 'price desc';
        }else if($price_type==2){
            $order = 'price';
        }else if($price_type==3){
            $price_start = intval(I('get.price_start'));
            $price_end = intval(I('get.price_end'));
            $map['price'] = array('between',array($price_start,$price_end));
        }

        $sell_num_type = intval(I('get.sell_num'));
        if($sell_num_type==1){
            $order = 'sales_num desc';
        }else if($sell_num_type==2){
            $order = 'sales_num';
        }else if($sell_num_type==3){
            $sell_num_start = intval(I('get.sell_num_start'));
            $sell_num_end = intval(I('get.sell_num_end'));
            $map['sales_num'] = array('between',array($sell_num_start,$sell_num_end));
        }

        !empty($shop_id) && $map['shop_id'] = $shop_id;
        !empty($cid) && $map['cate_id'] = $cid;

        $list = $this->model->getList($map,$order,20);
        foreach ($list['data'] as &$val){
            $val['cate'] = D('Common/ProductCate')->detail($val['cate_id'],'title');
            $val['shop'] = D('Common/Shop')->detail($val['shop_id'])['title'];
        }

        $this->assign($list);
        $this->assign('sort',$sort);
        $this->assign('keywords',$keywords);
        $this->assign('status',$status);
        $this->assign('stock',$stock);
        $this->assign('cid',$cid);
        $this->assign('price',$price_type);
        $this->assign('price_start',$price_start);
        $this->assign('price_end',$price_end);
        $this->assign('sell_num',$sell_num_type);
        $this->assign('sell_num_start',$sell_num_start);
        $this->assign('sell_num_end',$sell_num_end);
        $this->assign('shop_id',$shop_id);

        $this->getCateList();
        $this->getShopList();

        $this->display('index');
    }
    
    private function getCateList(){
        if($this->isSysAdmin){
            $cateList = D('Common/ProductCate')->getAllProductCate();
        } else {
            $cateList = D('Common/ProductCate')->getAllStoreProductCate($this->manage_id);
        }
        
        $this->assign('cateList',$cateList);
    }

    private function getShopList(){
        $shopList = D('Common/Shop')->getShopList($this->isSysAdmin ? 1 : $this->manage_id);
        $this->assign('shopList',$shopList);
    }

    public function edit(){
        $id = I('get.id',0,'intval');
        
        if($id){
            $detail = $this->model->detail($id);
            if($detail['attr']){
                $detail['attr'] = unserialize($detail['attr']);
            }
            if(empty($detail)) toErrorPage();
            $this->assign($detail);
            $this->getCateList();
        }
        $this->getShopList();
        
        $this->display('edit');
    }
    
    public function update(){
        $id = I('post.id');
        $shop_id = I('post.shop_id',0,'intval');//所属店铺
        $cate_id = I('post.cate_id',0,'intval');//商品分类
        $title = I('post.title','','trim');//商品名称
        $desc = I('post.desc');//商品描述
        $pic = I('post.pic');//商品图片
        $store = I('post.store',0,'intval');//库存
        $unit = I('post.unit');//单位
        $price = I('post.price',0,'trim');//价格
        $is_signature = I('post.is_signature',0,'intval');//是否为招牌菜，1=是，2=否
        $chili = I('post.chili',0);//加辣程度
        $has_attr = I('post.has_attr',0,'intval');//有无规格

        if($id){
            $info = $this->model->detail($id);
            if(empty($info)){
                $this->returnData('此商品不存在');
            }
        }

        if(empty($shop_id)){
            $this->returnData('请选择所属店铺');
        }
        $shopDetail = D('Common/Shop')->detail($shop_id);
        if(empty($shopDetail)){
            $this->returnData('不存在所选的店铺');
        }

        if(empty($cate_id)){
            $this->returnData('请选择商品分类');
        }
        $cateDetail = D('Common/ProductCate')->detail($cate_id);
        if(empty($cateDetail)){
            $this->returnData('不存在所选商品分类');
        }
        if(empty($title)){
            $this->returnData('商品名称不能为空');
        }
        if(abslength($title) > 30){
            $this->returnData('商品名称不能超过30个字');
        }
        
        if(abslength($desc) > 200){
            $this->returnData('商品不能超过200个字');
        }

        if(empty($pic) || !is_array($pic)){
            $this->returnData('请上传商品图片');
        }
        if(count($pic) >9 ){
            $this->returnData('商品图片不能超过9张');
        }

        if($store < 0){
            $this->returnData('库存不能小于0');
        }
        if($store > 9999999999){
            $this->returnData('库存超过最大限制9999999999');
        }

        if(empty($unit)){
            $this->returnData('单位不能为空');
        }
        if(abslength($unit) > 10){
            $this->returnData('单位不能超过10个字');
        }

        if(!isRegularPrice($price,true)){
            $this->returnData('价格格式错误！');
        }

        if($is_signature != 1 && $is_signature != 2){
            $this->returnData('请选择是否为招牌菜');
        }

        if($has_attr == 1){
            $spec_key = I('post.spec_key');//规格标识符
            $spec_name = I('post.spec_name');//规格名称
            $spec_price = I('post.spec_price');//规格价格
            //$spec_store = I('post.spec_store');//规格库存
            $spec_unit = I('post.spec_unit');//规格单位


            $specCount = count($spec_name);
            if(empty($spec_name) || empty($spec_price) || empty($spec_unit) ||
            !is_array($spec_price) || !is_array($spec_unit) || $specCount != count($spec_price)
            || $specCount != count($spec_key)){
                $this->returnData('规格数据错误');
            }

            $specStore = 0;
            $spec = array();
            for($i=0;$i<$specCount;$i++){
                if(empty($spec_key[$i])){
                    $spec_key[$i] = $this->getSpecKey();
                }
                if(empty($spec_name[$i])){
                    $this->returnData('规格名称不能为空');
                }
                if(abslength($spec_name[$i]) > 5){
                    $this->returnData('规格名称不能超过5个字');
                }
                if(!isRegularPercentage($spec_price[$i],true)){
                    $this->returnData('规格价格错误');
                }
                /*if(!preg_match('/^\d{0,10}$/',$spec_store[$i])){
                    $this->returnData('规格库存错误');
                }*/
                if(empty($spec_unit[$i])){
                    $this->returnData('规格单位错误');
                }
                //$specStore += $spec_store[$i];

                $spec[] = array(
                    'key' => $spec_key[$i],
                    'name' => $spec_name[$i],
                    'price' => $spec_price[$i],
                    //'store' => $spec_store[$i],
                    'unit'=>$spec_unit[$i],
                );
            }

            /*if($specStore != $store){
                $this->returnData('规格库存相加总和与库存总数不符');
            }*/

            $spec = serialize($spec);
        } else {
            $spec = '';
        }

        $data = array();
        $data['shop_id'] = $shop_id;
        $data['title'] = $title;
        $data['cate_id'] = $cate_id;
        
        $data['pic'] = implode(',',$pic);
        $data['store'] = $store;
        $data['unit'] = $unit;
        $data['desc'] = $desc;
        $data['price'] = $price;
        $data['is_signature'] = $is_signature;
        $data['attr'] = $spec;
        $data['edit_time'] = NOW_TIME;
        $data['chili'] = $chili;
        if($id){
            $data['id'] = $id;
            $msg = '修改';
        }else{
            $data['add_time'] = NOW_TIME;
            $data['uid'] = $this->manage_id;
            $msg = '添加';
        }

        $result = $this->model->update($data,$id);

        if($result){
            $result && D('Common/Product')->clearCache($id? $id : $result);
            $this->addHistoryLog($msg.'商品成功！');
            $this->returnData($msg.'成功！',1);
        }else{
            $this->returnData($msg.'失败！');
        }
    }

    private function getSpecKey(){
        return md5('product_spec_'.uniqid().mt_rand(0,999999));
    }

    /**
     * 上架
     */
    public function putaway(){
        $id = I('post.id',0,'intval');
        if(empty($id)){
            $this->returnData('请选择上架的商品');
        }

        $info = $this->model->detail($id);
        if(empty($info)){
            $this->returnData('此商品不存在');
        }

        if($info['is_on'] == 1){
            $this->returnData('此商品已上架');
        }
        
        $res = $this->model->putaway($id);
        
        if($res){
            D('Common/Product')->clearCache($id);
            $this->addHistoryLog('上架商品成功');
            $this->returnData('操作成功',1);
        } else {
            $this->returnData('操作失败');
        }
    }

    /**
     * 下架
     */
    public function soldOut(){
        $id = I('post.id',0,'intval');
        $reason = I('post.reason');

        if(empty($id)){
            $this->returnData('请选择下架的商品');
        }

        $info = $this->model->detail($id);
        if(empty($info)){
            $this->returnData('此商品不存在');
        }

        if($info['is_on'] == 2){
            $this->returnData('此商品已下架');
        }
        
        if(empty($reason)){
            $this->returnData('下架理由不能为空');
        }
        if(abslength($reason) > 200){
            $this->returnData('下架理由不能超过200个字');
        }

        $res = $this->model->soldOut($id,$reason);

        if($res){
            D('Common/Product')->clearCache($id);
            $this->addHistoryLog('下架商品成功');
            $this->returnData('操作成功',1);
        } else {
            $this->returnData('操作失败');
        }
    }

    /**
     * 获取商品分类
     */
    public function getProductCateList(){
        $shop_id = I('get.sid');
        if(empty($shop_id)) $this->returnData('数据错误!');
        $list = D('Common/ProductCate')->getStoreProductCate($shop_id);
        empty($list) && $this->returnData('该分店暂无商品分类!');

        $html = '<option value="">==请选择==</option>';
        $str = '<li class="selected" v="" style="width: 175px; margin: 0px; padding: 0px 25px 0px 10px;">==请选择==</li>';
        foreach($list as $val){
            $html .='<option value="'.$val['id'].'">'.$val['title'].'</option>';
            $str .='<li v="'.$val['id'].'" style="width: 175px; margin: 0px; padding: 0px 25px 0px 10px;">'.$val['title'].'</li>';
        }
        $this->returnData('',1,array('html'=>$html,'str'=>$str));
    }
}
?>